package cs304.p3.library.view;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import cs304.p3.library.controller.CheckOutBookController;
import cs304.p3.library.framework.IoC;
import cs304.p3.library.model.CheckOutBookForm;
import cs304.p3.library.util.FixedSizeNumberDocument;

@SuppressWarnings("serial")
public class CheckOutBookDialog extends JDialog{
	
	private MainFrame parent;
	private JTextField callField;
	private CheckOutBookController controller = IoC.resolve(CheckOutBookController.class);
	private CheckOutBookForm form = controller.getCheckOutBookForm();
	
	public CheckOutBookDialog(MainFrame frame, String title){
		super(frame, title);
		parent = frame;
		
		//Construct and add the components
		JPanel contentPane = new JPanel();
		setContentPane(contentPane);
		GridBagLayout gb = new GridBagLayout();
		GridBagConstraints c = new GridBagConstraints();
		contentPane.setLayout(gb);
		contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
		
		JLabel callLabel = new JLabel("Call Number: ");
		callField = new JTextField(8);
		callField.setDocument(new FixedSizeNumberDocument(callField, 8));
		
		//Call Number
		c.gridwidth = GridBagConstraints.RELATIVE;
		c.insets = new Insets(10, 15, 5, 0);
		gb.setConstraints(callLabel, c);
		contentPane.add(callLabel);
		c.gridwidth = GridBagConstraints.REMAINDER;
		c.insets = new Insets(10, 0, 5, 10);
		gb.setConstraints(callField, c);
		contentPane.add(callField);
		//Add button
		JButton addButton = new JButton("Add");
		addButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				form.setCallNumber(callField.getText());
				controller.performAction();
				CheckOutBookDialog.this.setVisible(false);
				CheckOutBookDialog.this.dispose();
				parent.updateDBTables();
			}
			
		});
		c.gridwidth = GridBagConstraints.REMAINDER;
		c.insets = new Insets(20, 20, 10, 10);
		gb.setConstraints(addButton, c);
		contentPane.add(addButton);
		
		//Finalize and show
		pack();
		setResizable(false);
		Point loc = frame.getLocationOnScreen();
		Dimension d = frame.getSize();
		setLocation(loc.x + (d.width - getWidth())/2, loc.y + (d.height - getHeight())/2);
	  	setDefaultCloseOperation(DISPOSE_ON_CLOSE);
	    setVisible(true);
	    callField.requestFocus();
	}

}
